<template>
  <div>
    <el-input
      type="textarea"
      :autosize="{ minRows: 5, maxRows: 100}"
      placeholder="请输入推荐详情"
      @input="fnValueChange"
      v-model="content"
    ></el-input>
    <div style="display: flex">
      <el-upload class="upload-demo" multiple :show-file-list="false" :http-request="addImage">
        <el-button size="small">添加图片</el-button>
      </el-upload>
      <el-upload class="upload-demo" multiple :show-file-list="false" :http-request="addVideo">
        <el-button size="small">添加视频</el-button>
      </el-upload>
      <el-button class="btn" @click="dialogFormLink = true" size="small">添加链接</el-button>
      <!--            <el-button class="btn" @click="formatRichText" size="small">数据格式化</el-button>-->
    </div>
    <div style="line-height: 1" v-if="richImg.length > 0">
      <h4>图片</h4>
      <ul class="img_ul">
        <li class="img_li" v-for="item in richImg" :key="item.index">
          <img :src="item.link" alt />
          <i @click="removeImg(item.index)" class="el-icon-delete img_delete"></i>
        </li>
      </ul>
    </div>
    <div style="line-height: 1" v-if="richVideo.length > 0">
      <h4>视频</h4>
      <ul class="img_ul">
        <li class="img_li" v-for="item in richVideo" :key="item.index">
          <video width="100" height="100" controls>
            <source :src="item.link" type="video/mp4" />
          </video>
          <i @click="removeVideo(item.index)" class="el-icon-delete img_delete"></i>
        </li>
      </ul>
    </div>
    <div style="line-height: 1" v-if="richLink.length > 0">
      <h4>链接</h4>
      <span v-for="item in richLink" :key="item.index" style="margin-right: 20px;">
        Link{{item.index}}
        <i
          @click="removeLink(item.index)"
          class="el-icon-delete img_delete"
          style="position: relative;margin-left: 10px;font-size: 14px;top:0;left: 0;right: 0;"
        ></i>
      </span>
    </div>

    <el-dialog title="添加链接" :visible.sync="dialogFormLink" width="40%">
      <el-form label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="linkObj.title"></el-input>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="linkObj.link"></el-input>
        </el-form-item>
        <el-form-item label="详情">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="linkObj.content"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            :show-file-list="false"
            :http-request="(fileObj) => addImage(fileObj, 'link')"
          >
            <img v-if="linkObj.imageUrl" :src="linkObj.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormLink = false">取 消</el-button>
        <el-button type="primary" @click="addLink">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const COS = require("cos-js-sdk-v5");
import { getAuthorization } from "@/api/admin";
export default {
  name: "simple-rich",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      content: "",
      richImg: [],
      richVideo: [],
      richLink: [],
      imgIndex: 0,
      videoIndex: 0,
      linkIndex: 0,

      // 腾讯云上传
      cos: null,

      // 链接
      dialogFormLink: false,
      linkObj: {
        title: "",
        link: "",
        content: "",
        imageUrl: "",
      },
    };
  },
  created() {
    this.cos = new COS({
      // 必选参数
      getAuthorization: async (options, callback) => {
        const { data } = await getAuthorization({
          bucket: process.env.VUE_APP_BUCKET,
          region: process.env.VUE_APP_REGION,
        });
        callback({
          TmpSecretId: data.credentials.tmpSecretId,
          TmpSecretKey: data.credentials.tmpSecretKey,
          XCosSecurityToken: data.credentials.sessionToken,
          ExpiredTime: data.expiredTime, // SDK 在 ExpiredTime 时间前，不会再次调用 getAuthorization
        });
      },
    });
  },
  watch: {
    value: function () {
      this.formatInputToContent(this.value);
    },
  },
  methods: {
    // 上传
    fnUpload(fileObj) {
      return new Promise((resolve, reject) => {
        const file = fileObj.file;
        const fileName = `${new Date().getTime()}${file.name}`;
        this.cos.putObject(
          {
            Bucket: process.env.VUE_APP_BUCKET /* 必须 */,
            Region: process.env.VUE_APP_REGION /* 必须 */,
            Key: process.env.VUE_APP_UPLOAD_PATH + fileName /* 必须 */,
            Body: file, // 上传文件对象
            onProgress: (progressData) => {
              if (progressData.percent === 1) {
                const url = `https://${process.env.VUE_APP_BUCKET}.cos.${process.env.VUE_APP_REGION}.myqcloud.com${process.env.VUE_APP_UPLOAD_PATH}${fileName}`;
                resolve(url);
              }
            },
          },
          function (err, data) {
            console.log(err || data);
            reject(err || data);
          }
        );
      });
    },
    fnValueChange() {
      this.formatRichText();
    },
    // 格式化数据
    formatRichText() {
      const ary = this.content.split("&+&");
      const result = [];
      ary.forEach((item) => {
        if (item !== "") {
          if (item.indexOf("<img") > -1) {
            const tempObj = this.richImg.filter((imgItem) => {
              return item === `<img${imgItem.index}>`;
            });
            result.push({
              type: "img",
              content: tempObj[0].link,
            });
          } else if (item.indexOf("<video") > -1) {
            const tempObj = this.richVideo.filter((videoItem) => {
              return item === `<video${videoItem.index}>`;
            });
            result.push({
              type: "video",
              content: tempObj[0].link,
            });
          } else if (item.indexOf("<link") > -1) {
            const tempObj = this.richLink.filter((linkItem) => {
              return item === `<link${linkItem.index}>`;
            });
            result.push({
              type: "link",
              content: tempObj[0].link,
            });
          } else {
            result.push({
              type: "text",
              content: item,
            });
          }
        }
      });
      // this.$emit('formatData', result)
      this.$emit("input", result);
    },
    // 添加图片
    async addImage(fileObj, type) {
      const url = await this.fnUpload(fileObj);
      if (type && type === "link") {
        this.linkObj.imageUrl = url;
        return;
      }
      this.richImg.push({
        index: this.imgIndex,
        type: "img",
        link: url,
      });
      this.content =
        (this.content ? this.content : "") + `&+&<img${this.imgIndex}>&+&`;
      this.imgIndex++;
      this.formatRichText();
    },
    // 删除图片
    removeImg(index) {
      this.content = this.content.replace(`&+&<img${index}>&+&`, "");
      let i = 0;
      for (; i < this.richImg.length; i++) {
        if (index === this.richImg[i].index) {
          break;
        }
      }
      this.richImg.splice(i, 1);
      if (this.richImg.length === 0) {
        this.imgIndex = 0;
      }
      this.formatRichText();
    },
    // 添加视频
    async addVideo(fileObj) {
      const url = await this.fnUpload(fileObj);
      this.richVideo.push({
        index: this.videoIndex,
        type: "video",
        link: url,
      });
      this.content =
        (this.content ? this.content : "") + `&+&<video${this.videoIndex}>&+&`;
      this.videoIndex++;
      this.formatRichText();
    },
    // 删除视频
    removeVideo(index) {
      this.content = this.content.replace(`&+&<video${index}>&+&`, "");
      let i = 0;
      for (; i < this.richVideo.length; i++) {
        if (index === this.richVideo[i].index) {
          break;
        }
      }
      this.richVideo.splice(i, 1);
      if (this.richVideo.length === 0) {
        this.videoIndex = 0;
      }
      this.formatRichText();
    },
    // 添加链接
    addLink() {
      this.richLink.push({
        index: this.linkIndex,
        type: "link",
        link: JSON.parse(JSON.stringify(this.linkObj)),
      });
      this.content =
        (this.content ? this.content : "") + `&+&<link${this.linkIndex}>&+&`;
      this.linkIndex++;
      this.dialogFormLink = false;
      this.linkObj = {
        title: "",
        link: "",
        content: "",
        imageUrl: "",
      };
      this.formatRichText();
    },
    // 删除链接
    removeLink(index) {
      this.content = this.content.replace(`&+&<link${index}>&+&`, "");
      let i = 0;
      for (; i < this.richLink.length; i++) {
        if (index === this.richLink[i].index) {
          break;
        }
      }
      this.richLink.splice(i, 1);
      if (this.richLink.length === 0) {
        this.linkIndex = 0;
      }
      this.formatRichText();
    },

    formatInputToContent(data) {
      this.content = "";
      this.richImg = [];
      this.richVideo = [];
      this.richLink = [];
      this.imgIndex = 0;
      this.videoIndex = 0;
      this.linkIndex = 0;
      data.forEach((item) => {
        if (item.type === "text") {
          this.content += item.content;
        } else if (item.type === "img") {
          this.richImg.push({
            index: this.imgIndex,
            type: "img",
            link: item.content,
          });
          this.content += `&+&<img${this.imgIndex}>&+&`;
          this.imgIndex++;
        } else if (item.type === "video") {
          this.richVideo.push({
            index: this.videoIndex,
            type: "video",
            link: item.content,
          });
          this.content += `&+&<video${this.videoIndex}>&+&`;
          this.videoIndex++;
        } else {
          this.richLink.push({
            index: this.linkIndex,
            type: "link",
            link: item.content,
          });
          this.content += `&+&<link${this.linkIndex}>&+&`;
          this.linkIndex++;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.btn {
  height: 32px;
  margin-top: 5px;
}

.el-form-item {
  margin-bottom: 10px;
}

.img_ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
}

.img_li {
  margin-right: 10px;
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;

  & > img {
    width: 100%;
    height: 100%;
  }
}

.img_delete {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 25px;
  color: red;
  cursor: pointer;
}

h4 {
  margin: 10px 0;
  line-height: 1.2;
}
</style>
